<?php
// Modules and libraries loader and controller
class qLoader
{
    private static $modules = array();
    private static $libraries = array();
    
    public static function Init()
    {
    	require_once "loader/moduleinfo.class.php";
        require_once "logger/logger.class.php";
        require_once "abstract/abstract.lib.php";
		qLoader::LoadLibrary("controllers");
    }
    
    public static function LoadFromConfig($config)
    {
        $modules = explode(';', $config->modules);
        foreach ($modules as $module)
        	self::_load($module, true);
        	
        $libraries = explode(';', $config->libraries);
        foreach ($libraries as $library)
        	self::_load($library, false);
    }
    
    public static function LoadModule($name, $parent)
    {
        return self::_load($name, true, $parent);
    }
    
    public static function LoadLibrary($name)
    {
    	return self::_load($name, false);    
    }
    private static function _load($name, $ismodule, $parent = null)
    {
    	if ((self::GetModule($parent != null ? $parent->Parents().'/' : ''.$name) != false && $parent != null) || (isset(self::$libraries[$name]) && !$ismodule)) 
    		return true;
    	
    	if ($parent == null || ($parent != null && $ismodule = false))
    	   	$filename = ($ismodule ? modules_path : lib_path) . '/' . $name . '/' . $name . '.' . ($ismodule ? 'module' : 'lib') . '.php';
        else
        	$filename = modules_path . '/' . $parent->Parents() . '/' . $parent->Name() . '/' . $name . '/' . $name . '.module.php';
        
        if (!file_exists($filename))
        {
        	// LOG: Module/lib not found.
        	return false;	    
        }
        
        require_once $filename;
        
        if ($ismodule)
        {
	        $module = new $parent != null ? str_replace('/', '::', $parent->Parents().'/'.$parent->Name()) : ''.$name;
        
    	    if (!($module instanceof qModule))
        	{
            	// LOG: Module object is not instance of qModule/qLibrary.
	            return false;
    	    }
    	    
    	    if ($parent != null)
		   	    $parent->AddSubmodule($name, $module);
		   	else
		   		self::$modules[$name] = new qModuleInfo($name, $module);
        
        	$module->Init();
        }
        
		if (!$ismodule)
        	self::$libraries[$name] = true;
        	
        return true;
    }
    
    public static function GetModule($name)
    {
    	if (isset(self::$modules[$name]))
    		return self::$modules[$name];
    	else
    	{
    	    foreach (self::$modules as $module)
    	    {
    	        if ($module = $module->SearchForSubmodule($name))
    	        	return $module;
    	    }
    	}
    	
    	return false; 
    }
}